<?php

namespace App\Http\Controllers;

use App\Models\Photo;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class PhotoController extends Controller
{
    /**
     * 前台：获取所有图片
     */
    public function publicIndex(): JsonResponse
    {
        $photos = Photo::orderBy('created_at', 'desc')->get();
        return response()->json([
            'data' => $photos,
            'message' => $photos->isEmpty() ? '暂无图片' : '获取图片成功',
        ], 200);
    }

    /**
     * 后台：分页+搜索图片列表（返回格式与标签一致）
     */
    public function adminIndex(Request $request): JsonResponse
    {
        $query = Photo::query();
        if ($search = $request->input('search')) {
            $query->where(function($q) use ($search) {
                $q->where('title', 'like', "%$search%")
                  ->orWhere('description', 'like', "%$search%")
                  ->orWhere('alt_text', 'like', "%$search%")
                  ;
            });
        }
        $perPage = $request->input('per_page', 10);
        $photos = $query->orderBy('created_at', 'desc')->paginate($perPage);
        return response()->json([
            'data' => $photos->items(),
            'meta' => [
                'current_page' => $photos->currentPage(),
                'per_page' => $photos->perPage(),
                'total' => $photos->total(),
                'last_page' => $photos->lastPage(),
                'from' => $photos->firstItem(),
                'to' => $photos->lastItem(),
            ],
            'links' => [
                'first' => $photos->url(1),
                'last' => $photos->url($photos->lastPage()),
                'prev' => $photos->previousPageUrl(),
                'next' => $photos->nextPageUrl(),
            ],
            'message' => '成功获取图片列表',
        ], 200);
    }

    /**
     * 获取单个图片详情
     *
     * @param Photo $photo
     * @return JsonResponse
     */
    public function show(Photo $photo): JsonResponse
    {
        return response()->json([
            'data' => $photo,
            'message' => '获取图片详情成功',
        ], 200);
    }

    /**
     * 创建新图片记录
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'url' => 'required|string',
            'alt_text' => 'nullable|string|max:255',
        ]);

        $photo = Photo::create($validated);

        return response()->json([
            'data' => $photo,
            'message' => '图片创建成功',
        ], 201);
    }

    /**
     * 更新图片信息
     *
     * @param Request $request
     * @param Photo $photo
     * @return JsonResponse
     */
    public function update(Request $request, Photo $photo): JsonResponse
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'url' => 'required|string',
            'alt_text' => 'nullable|string|max:255',
        ]);

        $photo->update($validated);

        return response()->json([
            'data' => $photo,
            'message' => '图片更新成功',
        ], 200);
    }

    /**
     * 删除图片
     *
     * @param Photo $photo
     * @return JsonResponse
     */
    public function destroy(Photo $photo): JsonResponse
    {
        // 删除文件（如果存在）
        if ($photo->url && Storage::disk('public')->exists($photo->url)) {
            Storage::disk('public')->delete($photo->url);
        }

        $photo->delete();

        return response()->json([
            'message' => '图片删除成功',
        ], 200);
    }

}
